package com.gamemost.templestay;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Map;
import java.util.Random;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.gamemost.templestay.NanoHTTPD.Response.Status;

public class ImageServer extends NanoHTTPD {
	Context mContext;

	public ImageServer(String host, Context context) {
		super(host, 8080);
		this.mContext = context;
	}

	Status HTTP_OK = Status.OK;
	public static final String MIME_PLAINTEXT = "text/plain",
			MIME_HTML = "text/html", MIME_JS = "application/javascript",
			MIME_CSS = "text/css", MIME_PNG = "image/png",
			MIME_DEFAULT_BINARY = "application/octet-stream",
			MIME_XML = "text/xml";
	public static String TAG = "ImageServer";

	@Override
	public Response serve(String uri, Method method,
			Map<String, String> headers, Map<String, String> parms,
			Map<String, String> files) {
		// TODO Auto-generated method stub
		System.out.println("request get " + method + " '" + uri + "' ");
		final StringBuilder buf = new StringBuilder();
		for (java.util.Map.Entry<String, String> kv : headers.entrySet())
			buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
		InputStream mbuffer = null;
		try {
			if (uri != null) {

				if (uri.contains(Environment.getExternalStorageDirectory()
						.getPath())) {

					File request = new File(uri);
					mbuffer = new FileInputStream(request);
					FileNameMap fileNameMap = URLConnection.getFileNameMap();
					String mimeType = fileNameMap.getContentTypeFor(uri);
					Log.d(TAG, mimeType + " request for media on sdCard " + uri);

					Response streamResponse = new Response(HTTP_OK, mimeType,
							mbuffer);
					Random rnd = new Random();
					String etag = Integer.toHexString(rnd.nextInt());
					streamResponse.addHeader("ETag", etag);
					streamResponse.addHeader("Connection", "Keep-alive");
					return streamResponse;
				} else {
					Response res = new NanoHTTPD.Response(Status.BAD_REQUEST,
							MIME_HTML, mbuffer);
					Random rnd = new Random();
					String etag = Integer.toHexString(rnd.nextInt());
					res.addHeader("ETag", etag);
					res.addHeader("Connection", "Keep-alive");
					return res;

				}
			}

		} catch (IOException e) {
			Log.d(TAG, "Error opening file" + uri.substring(1));
			e.printStackTrace();
		}

		return null;

	}
}
